<template>
  <a-config-provider>
    <a-modal
      :title="title"
      :width="1000"
      :body-style="{padding:'24px 74px 24px 24px'}"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭">

      <a-spin :spinning="confirmLoading">
        <a-form-model :model="model" :rules="validatorRules" :label-col="labelColX2" :wrapper-col="wrapperColX2" ref="ruleForm">
          <a-divider orientation="left" style="margin-bottom: 40px">基本信息</a-divider>
          <a-row style="width: 100%;">
            <a-col :span="12">
              <a-form-model-item label="日程标题" prop="title">
                <a-input placeholder="请输入标题" :disabled="allReadOnly" :read-only="allReadOnly" v-model="model.title"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="日程类型" prop="type">
                <j-dict-select-tag placeholder="请选择类型" type="select"  :disabled="allReadOnly" v-model="model.type" dictCode="eoa_plan_type"/>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row style="width: 100%;">
            <a-col :span="12">
              <a-form-model-item label="提醒类型" prop="remindType">
                <a-select placeholder="请选择提醒类型" mode="multiple" :disabled="allReadOnly" v-model="model.remindType">
                  <a-select-option value="4">系统消息</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="紧急程度" prop="urgentLevel">
                <j-dict-select-tag placeholder="请选择紧急程度" :disabled="allReadOnly" type="select"  v-model="model.urgentLevel" dictCode="urgent_level"/>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row style="width: 100%;">
            <a-col :span="12">
              <a-form-model-item label="日程时间" prop="rangeTime">
                <a-range-picker 
                  v-bind="dateRangePickerProps"
                  :disabled="allReadOnly"
                  v-model="model.rangeTime"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-divider orientation="left" style="margin-bottom: 40px">其他信息</a-divider>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="颜色">
                <a-tooltip class="setting-drawer-theme-color-colorBlock" v-for="(item, index) in colorList" :key="index">
                  <template slot="title">
                    {{ item.key }}
                  </template>
                  <a-tag :color="item.color" @click="changeColor(item.color)" :disabled="allReadOnly">
                    <a-icon type="check" v-if="item.color === primaryColor"></a-icon>
                  </a-tag>
                </a-tooltip>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="参与人" prop="joinPerson">
                <j-select-user-by-dep v-model="model.joinPerson" :disabled="allReadOnly" :multi="true" :backUser="true" @back="selectPeople"></j-select-user-by-dep>
                <a-input placeholder="" type="hidden" v-model="model.receiverIds"/>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row style="width: 100%;">
            <a-col :span="24">
              <a-form-model-item
                class="j-eoa-plan-field-remark"
                :labelCol="labelColX1"
                :wrapperCol="wrapperColX1"
                label="备注"
                prop="remark"
              >
                <j-editor
                  placeholder="请输入备注"
                  :disabled="allReadOnly"
                  v-model="model.remark"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-spin>
      <template slot="footer">
        <a-button type="primary" :loading="confirmLoading" :disabled="allReadOnly" @click="handleOk">
          保存
        </a-button>
        <a-popconfirm v-if="model.id && model.status == '0'" title="您确定要删除日程安排吗？" @confirm="handleDelete">
          <a-button type="danger" style="background-color:#FF7875" :loading="confirmLoading">删除</a-button>
        </a-popconfirm>
        <a-button type="dashed" @click="handleCancel" :loading="confirmLoading">取消</a-button>
      </template>
    </a-modal>
  </a-config-provider>
</template>

<script>
  import { httpAction, deleteAction } from '@/api/manage'
  import moment from 'moment'
  import { mapGetters } from 'vuex'
  import store from '@/store/'
  import JEditor from '@/components/jeecg/JEditor'
  import JCheckbox from '@comp/jeecg/JCheckbox'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
  import JMultiSelectTag from '@/components/dict/JMultiSelectTag'
  export default {
    name: 'EoaPlanModal',
    components: { JCheckbox, JEditor,JSelectUserByDep,JMultiSelectTag },
    data() {
      return {
        title: '操作',
        visible: false,
        defaultFormat: 'YYYY-MM-DD HH:mm:ss',
        model: {
          allDay: '',
          rangeTime: null
        },
        labelColX1: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperColX1: {
          xs: { span: 24 },
          sm: { span: 24 - 3 },
        },
        labelColX2: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperColX2: {
          xs: { span: 24 },
          sm: { span: 24 - 6 },
        },
        confirmLoading: false,
        validatorRules: {
          title: [{ required: true, message: '请输入标题!' }],
          remindType: [{ required: true, message: '请选择提醒类型!' }],
          rangeTime: [{ required: true, message: '请选择日程时间!' }],
          type: [{ required: true, message: '请选择日程类型!' }],
          urgentLevel: [{ required: true, message: '请选择紧急程度!' }],
          isNotEmpty: [{required:true,message:"该项不能为空!"}],
          joinPerson: [{required:true,message:"请选择参与人!"}],
        },
        allReadOnly: false,
        colorList: [
          { key: '薄暮', color: '#F5222D' },
          { key: '火山', color: '#FA541C' },
          { key: '日暮', color: '#FAAD14' },
          { key: '明青', color: '#13C2C2' },
          { key: '极光绿', color: '#52C41A' },
          { key: '拂晓蓝（默认）', color: '#1890FF' },
          { key: '极客蓝', color: '#2F54EB' },
          { key: '酱紫', color: '#722ED1' },
        ],
        primaryColor:'#1890FF',
        url: {
          add: '/api/erp/workbench/plan/add',
          edit: '/api/erp/workbench/plan/edit',
          delete: '/api/erp/workbench/plan/delete',
        },
      }
    },
    computed: {
      dateRangePickerProps() {
        return {
          style: {width:'100%'},
          showTime: {
            format: 'HH:mm',
            hideDisabledOptions: true,
            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('00:00:00', 'HH:mm:ss')]
          },
          disabledTime: () => {
            return {
              disabledMinutes: () => this.dateRange(0, 59).filter(i => !([0, 15, 30, 45].includes(i))),
            }
          },
          format: this.defaultFormat,
          getCalendarContainer: (el) => el.parentNode
        }
      },
    },
    methods: {
      //选择参与人员
      selectPeople(data){
        if(data){
          let receiverIds="";
          for(var i=0;i<data.length;i++){
            if(i==data.length-1){
              receiverIds+=data[i].empId;
            }else{
               receiverIds+=data[i].empId+",";
            }
          }
          this.$set(this.model,'receiverIds',receiverIds);
        }
      },
      dateRange(start, end) {
        const result = []
        for (let i = start; i <= end; i++) {
          result.push(i)
        }
        return result
      },
      /** 新增日程计划 */
      addEvent(start,end, view) {
        this.title = '新增日程计划'
        this.visible = true
        this.$set(this.model,'title',null)
        this.$set(this.model,'joinPerson',store.getters.userInfo.username)
        this.$set(this.model,'receiverIds',store.getters.userInfo.empId)
        this.$set(this.model,'type',null)
        this.$set(this.model,'urgentLevel',null)
        this.$set(this.model,'remark',null)
        this.$set(this.model,'planColor',null)
        let { type } = view
        if (type === 'dayGridMonth') {
          // 当显示月时，天数会自动加一天，故减一天
          var timestamp = end /1000;
          timestamp = (timestamp-86400)*1000;
          this.$set(this.model,'rangeTime',[start, moment(timestamp)]);
        } else if (type === 'timeGridWeek' || type === 'timeGridDay') {
          this.$set(this.model,'rangeTime',[start, end]);
        }
        this.model.allDay = ''
      },
      view(record) {
        this.allReadOnly = true
        this.edit(record, '查看日程计划')
      },
      add() {
        this.edit({}, '新增日程计划')
      },
      edit(record, title = '变更日程计划') {
        this.title = title
        this.visible = true
        this.model = Object.assign({}, record)
        if(record.id){
          this.primaryColor = this.model.planColor
          this.$set(this.model,'rangeTime',[moment(record.startTime),moment(record.endTime)])
          this.model.remindType = this.model.remindType.split(',')
        } else {
          this.$set(this.model,'joinPerson',store.getters.userInfo.username)
        }
      },
      close() {
        this.$emit('close')
        this.visible = false
        this.allReadOnly = false
        this.primaryColor='#1890FF';
        this.$refs.ruleForm.resetFields()
        this.model = {}
      },
      ...mapGetters(['userInfo']),
      handleOk() {
        const that = this
        console.log(this.model);
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.model.handlerId = this.userInfo().empId;
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign({},this.model)
            formData.remindType = formData.remindType.join(',')
            let times = formData.rangeTime.map(i => i ? i.format('YYYY-MM-DD HH:mm:ss') : null)
            formData.startTime = times[0]
            formData.endTime = times[1]
            formData.reminderTime = times[0] //提醒时间为开始时间
            if(times[0] > moment().format(this.defaultFormat)){
              formData.status = '0'
            }else{
              formData.status = '5'
            }
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.close()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
            })
          }
        });
      },
      handleCancel() {
        this.close()
      },
      handleDelete() {
        this.confirmLoading = true
        deleteAction(this.url.delete, { id: this.model.id }).then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.close()
            this.confirmLoading = false
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      },
      changeColor(color){
        this.primaryColor = color;
        this.model.planColor = color
      }
    }
  }
</script>

<style lang="less" scoped>
  .j-eoa-plan-field-remark {

    /deep/ button[title='插入/编辑图片'],
    /deep/ button[title='插入/编辑媒体'] {
      display: none;
    }

    /deep/ .tox.tox-tinymce {
      min-height: 200px;
    }

  }
  .setting-drawer-theme-color-colorBlock {
    width: 20px;
    height: 20px;
    border-radius: 2px;
    cursor: pointer;
    float: left;
    margin-right: 8px;
    padding-left: 0;
    padding-right: 0;
    text-align: center;
    color: #fff;
    font-weight: 700;
    margin-top: 10px;
    i {
      font-size: 14px;
    }
  }
</style>